package cn.com.elite;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.sql.Types;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.UUID;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPClientConfig;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import cn.com.elite.Util;

public class EliteRecordFtpService extends HttpServlet{
	private static final Log log=LogFactory.getLog(EliteRecordFtpService.class);
	private static String ContentType;
	private static cn.com.elite.EliteBean ebean;
	private static String ContextPath="";
	private static String CMDcommand="";
	
	public EliteBean getbean(){
		ServletContext application=getServletContext();   
        WebApplicationContext wac=WebApplicationContextUtils.getWebApplicationContext(application);
        cn.com.elite.EliteBean ebean=(cn.com.elite.EliteBean)wac.getBean("ebean");  
        return ebean;
	} 
	
	public void init(){
		try{
			ContentType=this.getInitParameter("ContentType");
			log.info("ContentType:"+ContentType);
			ContextPath=this.getInitParameter("ContextPath");
			log.info("ContextPath:"+ContextPath);
			CMDcommand=this.getInitParameter("CMDcommand");
			log.info("CMDcommand:"+CMDcommand);
			ebean=getbean();
			log.info("服务初始化读取配置文件完成");
		}catch(Exception e){
			log.error("服务初始化读取配置文件错误");
			log.error(Util.getERRO(e));
		}
	}
	private FTPClient GetFtp(String host,int port,String username,String password){
		FTPClient ftp=new FTPClient();
		try{
			ftp.connect(host,port); 			
			ftp.login(username, password);
			return ftp;
		}catch(Exception e){
			log.error("FTP获取失败");
			log.error(Util.getERRO(e));
			return null;
		}
	}
	public String downloadfile(String path,String host,int port,String username,String password) throws Exception{
		FTPClient ftp=GetFtp(host,port,username,password);
		String name=ContextPath+path.substring(path.lastIndexOf("\\"),path.length());
		log.debug("filename:"+name);
		File file=new File(name);
		FileOutputStream fos=new FileOutputStream(file);
		boolean flag=ftp.retrieveFile(path,fos);
		log.debug("ftp.retrieveFile:"+flag);
		fos.close();
		ftp.disconnect();
		return name;
	}
	public String GetFtpParam(String path,String FtpPath) throws Exception{
		String sql="select * from T_Path where Path_O=?";
		int[] types=new int[]{Types.VARCHAR};
		Object[] params=new Object[]{path+":"};
		List list=ebean.QueryPersonUseExecute(sql,types,params);
		if(list!=null&&list.size()>0){
			Map map=(Map)list.get(0);
			String Path_IP=(String)map.get("Path_IP");
			log.debug("Path_IP:"+Path_IP);
			String FTP_Port=(String)map.get("FTP_Port");
			log.debug("FTP_Port:"+FTP_Port);
			String Login_Name=(String)map.get("Login_Name");
			log.debug("Login_Name:"+Login_Name);
			String Login_Pwd=(String)map.get("Login_Pwd");
			log.debug("Login_Pwd:"+Login_Pwd);
			return downloadfile(FtpPath,Path_IP,Integer.parseInt(FTP_Port),Login_Name,Login_Pwd);
		}else{
			throw new Exception("select * from T_Path where Path_O=? is null");
		}
	}
	public String getFile(String agentid,String callid) throws Exception{
		String sql=" select FileName from FileDetail where AgentID=? and CallID=?";
		int[] types=new int[]{Types.VARCHAR,Types.VARCHAR};
		Object[] params=new Object[]{agentid,callid};
		List list=ebean.QueryPersonUseExecute(sql,types,params);
		if(list!=null&&list.size()>0){
			Map map=(Map)list.get(0);
			String FileName=(String)map.get("FileName");
			log.debug("FileName:"+FileName);
			String[] FileNameSplit=FileName.split(":");
			if(FileNameSplit!=null&&FileNameSplit.length==2){
				String path=FileNameSplit[0];
				log.debug("path:"+path);
				String FtpPath=FileNameSplit[1];
				log.debug("FtpPath:"+FtpPath);
				return GetFtpParam(path,FtpPath);
			}else{
				throw new Exception("FileName is wrong");
			}
		}else{
			throw new Exception("select FileName from FileDetail where AgentID=? and CallID=? is null");
		}
	}
	public void doGet(HttpServletRequest request, HttpServletResponse response){
		doPost(request,response);
	}
	public void doPost(HttpServletRequest request, HttpServletResponse response){
		try{
			log.debug("---------------doPost-----------------");
			String agentid=request.getParameter("agentid");
			log.debug("agentid:"+agentid);
			String[] callid=request.getParameterValues("callid");
			ArrayList arry=new ArrayList();
			String returnfliepath="";
			if(callid!=null&&callid.length>0){
				for(int i=0;i<callid.length;i++){
					String callidValue=callid[i];
					log.debug("callid["+i+"]:"+callidValue);
					String path=getFile(agentid,callidValue);
					log.debug("path:"+path);
					boolean flag=arry.add(path);
					log.debug("arry.add(path):"+flag);
				}
			}
			if(arry!=null&&arry.size()>0){
				if(arry.size()==1){
					returnfliepath=(String)arry.get(0);
				}else{
					String command=CMDcommand+" ";
					String temp=(String)arry.get(0);
					returnfliepath=ContextPath+"/"+UUID.randomUUID()+"_final.wav";
					for(int i=0;i<arry.size();i++){
						command+=(String)arry.get(i)+" ";
					}
					log.debug("temp:"+temp);
					command+="\""+returnfliepath+"\"";
			        log.debug("command:"+command);
			        Process process=Runtime.getRuntime().exec(command);
			        try{
			            int exitcode=process.waitFor();
			            if(exitcode==0){
			                log.debug("convert successfully");
			            }else{
			                log.debug("convert failed and return "+exitcode);
			            }
			            process.getInputStream().close();
			            process.getOutputStream().close();
			            process.getErrorStream().close();
			        }catch(InterruptedException ie){
			            log.error(Util.getERRO(ie));
			        }
					for(int i=0;i<arry.size();i++){
						File file=new File((String)arry.get(i));
						boolean result=file.delete();
						log.debug("file.delete():"+result);
					}
				}
			}
			request.setCharacterEncoding("UTF-8");
			response.setContentType(ContentType);
			response.setHeader("Content-disposition","attachment;filename="+returnfliepath.substring(returnfliepath.lastIndexOf("\\"),returnfliepath.length()));
			OutputStream output=response.getOutputStream();
	        InputStream in=new FileInputStream(returnfliepath); 
	        BufferedInputStream bis=new BufferedInputStream(in);//输入缓冲流
	        BufferedOutputStream bos=new BufferedOutputStream(output);//输出缓冲流
	        byte data[]=new byte[1024];//缓冲字节数
	        int size=0;
	        size=bis.read(data);
	        while(size!=-1){
	            bos.write(data,0,size);
	            size=bis.read(data);
	        }
	        bis.close();
	        bos.flush();//清空输出缓冲流
	        bos.close();
	        output.close();
		}catch(Exception e){
			log.error("doGet过程错误");
			log.error(Util.getERRO(e));	
			try {
				response.setContentType("text/html;charset=UTF-8");
		        PrintWriter out=response.getWriter();
		        out.print("doGet过程错误:"+Util.getERRO(e));
			} catch (IOException e1) {
				log.error("FTP关闭错误");
				log.error(Util.getERRO(e1));
			}
		}	
	}

}
